package com.bwie.controller;

import com.bwie.common.pojo.dto.UserDto;
import com.bwie.common.result.Result;
import com.bwie.common.utils.ImageVerificationCode;
import com.bwie.common.utils.OssUtil;
import com.bwie.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
public class AuthController {
    @Autowired
    private AuthService authService;
    @PostMapping("/login")
    private Result login(@RequestBody @Valid UserDto userDto){
        return authService.login(userDto);
    }
    /**
     * 注册
     */
    @PostMapping("/register")
    private Result register(@RequestBody @Valid UserDto userDto){
        return authService.register(userDto);
    }
    /**
     * 登录
     */
    @PostMapping("/newLogin")
    private Result newLogin(@RequestBody @Valid UserDto userDto){
        return authService.newLogin(userDto);
    }
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 图片验证码
     */
    @GetMapping("tupian")
    private void upload(OutputStream outputStream){
        ImageVerificationCode imageVerificationCode = new ImageVerificationCode();
        BufferedImage image = imageVerificationCode.getImage();
        String text = imageVerificationCode.getText();
        redisTemplate.opsForValue().set("imageCode",text,60*5, TimeUnit.MINUTES);
        try {
            ImageVerificationCode.output(image,outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 判断验证码是否正确
     */
    @PostMapping("/checkCode/{imgCode}")
    private Result checkCode(@PathVariable("imgCode") String code){
        String imageCode = (String) redisTemplate.opsForValue().get("imageCode");
        if (code.equals(imageCode)){
            return Result.success(null);
        }
        return Result.error("验证码错误");
    }
    @Autowired
    private OssUtil ossUtil;
    @PostMapping("uploads")
    private String uploads(@RequestBody MultipartFile file){
        String s = ossUtil.uploadMultipartFile(file);
        return s;
    }
}

